<?php
namespace Home\Controller;
use Think\Controller;
class OrgController extends Controller {
    public function index(){
        $this->display();
    }

    public function regAction(){
        if(IS_POST){
            $verify = new \Think\Verify();
            if($verify->check(I("post.code"),'')){
                $_POST['password']=md5(htmlspecialchars_decode(trim(I('post.password'))));
                $_POST['username']='admin'.(microtime(true)*10000);
                $_POST['lastlogintime']=time();
                $AdminModel=D('Admin');

                if (!$AdminModel->create($_POST)){
                    $info=$AdminModel->getError();
                }else{
                    $res=$AdminModel->where(array('email'=>I('post.email')))->find();
                    if(isset($res) && $res['state']==1){
                        $info="此邮箱已使用";
                    }else if(time()-$res['lastlogintime']<=60){
                        $info="请等待1分钟后，重新发送";
                    }else{
                        if(!isset($res)){
                                $new_id=$AdminModel->add();
                        }else{
                            M('Admin')->save(array('id'=>$res['id'],'lastlogintime'=>time()));
                            $new_id=$res['id'];
                        }

                        if($new_id){
                            $check['id']=$new_id;
                            $check['email']=I('post.email');
                            $check['time']=time();
                            $check['rand']=rand(10000,99999);
                            $hash=rawurlencode(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5(C('PWD_SALT')), json_encode($check), MCRYPT_MODE_ECB)));
                            $output=$this->sendRegEmail($hash,I('post.email'));
                            if($output['statusCode']==200 && $output['message']=='请求成功'){
                                $info="验证邮件已成功发送，请登录邮箱进行邮件验证！";
                            }else{
                                $info="验证邮件发送失败!";
                            }
                        }else{
                            $info="参数错误";
                        }
                    }
                }
            }else{
                $info="验证码错误!";
            }
        }else if(session('orgReg_sendEmail')){
            $info="验证邮件已成功发送，请登录邮箱进行邮件验证！";
        }else{
            header("Location:".U('index'));
        }
        $this->assign('info',$info);
        $this->display();
    }

    public function sendRegEmail($hash,$email){
        $api='http://api.sendcloud.net/apiv2/mail/sendtemplate';
        $url='http://'.I('server.HTTP_HOST').U('emailCheck')."?hash=".$hash;


        $post=array(
            'apiUser'=>'jianweiorgreg_k3HDbN',
            'apiKey'=>'BLm9mxnfenjPBTaS',
            'from'=>'user@mail.jianwei.com',
            'templateInvokeName'=>'organreg',
            'xsmtpapi'=>json_encode(array(
                "to"=>array($email),
                "sub"=>array(
                    "%url%"=>array($url)
                ),
            )),
            'fromName'=>'见微发稿|直播助手',
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $api);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        $output = curl_exec($ch);
        curl_close($ch);
        $output=json_decode($output,true);
        session('orgReg_sendEmail',true);
        session('orgReg_email',$email);
        return $output;
    }

    public function reSendEmail(){

        $hash=I('get.hash');
        $email=I('get.email');
        if($hash || $email){
            $key=md5(C('PWD_SALT'));
            if($hash){
                $check =json_decode(trim(mcrypt_decrypt( MCRYPT_RIJNDAEL_256,$key, base64_decode(rawurldecode($hash)), MCRYPT_MODE_ECB )),true);
                $email=$check['email'];
            }

            $info=M('Admin')->field('id,email,state,lastlogintime')->where(array('email'=>$email))->find();
            $check['email']=$email;
            $check['id']=$info['id'];
            $check['time']=time();
            $check['rand']=rand(10000,99999);

            if(!(isset($check['email']) && isset($check['time']) && isset($check['id']))){
                $mess['code']=false;
                $mess['info']="参数错误!";
            }else{

                if($info['state']==1)
                {
                    $mess['code']=false;
                    $mess['info']="您的邮箱已经激活!";
                }else{

                    M('Admin')->save(array('id'=>$check['id'],'lastlogintime'=>$check['time']));
                    $hash=rawurlencode(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5(C('PWD_SALT')), json_encode($check), MCRYPT_MODE_ECB)));
                    $output=$this->sendRegEmail($hash,$check['email']);
                    if($output['statusCode']==200 && $output['message']=='请求成功'){
                        $mess['code']=true;
                        $mess['info']="验证邮件已成功发送，请登录邮箱进行邮件验证！";
                    }else{
                        $mess['code']=false;
                        $mess['info']="验证邮件发送失败!";
                    }
                }
            }
        }else{
            $mess['code']=false;
            $mess['info']="参数错误!";
        }
        $this->ajaxReturn($mess);
    }

    public function queryEmail(){
        $email=$_POST["param"];
        $info=M('Admin')->field('email')->where(array('email'=>$email))->find();
        if(!$info){
            $mess['status']='y';
            $mess['info']='此邮箱可以使用！';
        }else{
            $mess['status']='n';
            $mess['info']='此邮箱已经使用！';
        }
        $this->ajaxReturn($mess);
    }

    public function emailCheck(){
        session('organ_id',null);
        $hash=I('get.hash');
        if($hash){
            $key=md5(C('PWD_SALT'));
            $check =json_decode(trim(mcrypt_decrypt( MCRYPT_RIJNDAEL_256,$key, base64_decode(rawurldecode($hash)), MCRYPT_MODE_ECB )),true);
            if(!(isset($check['email']) && isset($check['time']) && isset($check['id']))){
                $this->error("参数错误","/");
            }else{
                $info=M('Admin')->field('email,state,lastlogintime')->find($check['id']);
                if($info['state']==1)
                {
                    $this->error("您的邮箱已经激活","/");
                }else if($check['time']!=$info['lastlogintime'] || time()-$check['time']>60*30){
                    $this->error("此链接已经失效","/");
                }else{
                    $res=M('Admin')->save(array('id'=>$check['id'],'state'=>1));
                    if($res){
                        session('organ_id',$check['id']);
                        session('orgReg_email',$check['email']);
                        $this->success("验证成功！",U('setOrganInfo'));
                    }else{
                        $this->error("服务器错误","/");
                    }
                }
            }
        }else{
            $this->error("参数错误","/");
        }
    }

    /*public function login(){
        C('TOKEN_ON',false);
        if(IS_POST) {
            // 管理员登陆
            $is_admin = I('post.is_admin');
            if ($is_admin) {
                $data['email'] = I("post.email");
                $_POST['pass'] = md5(htmlspecialchars_decode(trim(I('post.password'))));
                if ($data['email'] && I("post.password")) {

                    $AdminModel = D('Admin');
                    if (!$AdminModel->create($_POST)) {
                        $this->error($AdminModel->getError());
                    } else {
                        $res = $AdminModel->where(array('email' => $data['email']))->find();
                        if ($res && $res['password'] == $_POST['pass']) {
                            if ($res['state'] == 0) {
                                session('orgReg_sendEmail', true);
                                session('orgReg_email', $data['email']);
                                $this->success('登录成功！', U('Org/regAction'));
                            } elseif ($res['state'] == 1 && !$res['organ']) {
                                session('organ_id', $res['id']);
                                session('is_admin', 1);
                                $this->success('登录成功！', U('Org/setOrganInfo'));
                            } else {
                                if (I('post.rememberPass') == 1) {
                                    session(array('expire' => 3600 * 24 * 90));
                                }
                                session('[regenerate]');
                                session('organ_login', true);
                                session('organ_id', $res['id']);
                                session('is_admin', 1);
                                //$this->success('登录成功！',U('Department/index'));
                                $this->success('登录成功！', U('Reporter/index'));
                            }
                        } elseif ($res && $res['password'] != $data['pass']) {
                            $this->error('密码错误！');
                        } else {
                            $this->error('email未注册！');
                        }
                    }
                } else {
                    $this->error('参数错误！');
                }
            } else {
                // 记者登陆
                $data['mobile']=I("post.email");
                $_POST['mobile'] = $_POST['email'];
                unset($_POST['email']);

                $_POST['pass']=md5(htmlspecialchars_decode(C('PWD_SALT') . trim(I('post.password'))));
                if($data['mobile'] && I("post.password")){
                    $UserInfoModel=D('UserInfo');
                    if (!$UserInfoModel->create($_POST)) {
                        $this->error($UserInfoModel->getError());
                    }else{
                        $res=$UserInfoModel->alias('ui')->join('__USER__ u ON ui.uid = u.uid')->where(array('mobile'=>$data['mobile']))->find();
                        if($res && $res['password']==$_POST['pass']){

                            $power = M('UserPower')->where(array('user_id' => $res['uid']))->select();
                            if(empty($power)) {
                                $this->error('您无权限登陆！',U('Index/login'));
                                exit;
                            } else {
                                if(I('post.rememberPass')==1){
                                    session(array('expire'=>3600*24*90));
                                }
                                session('[regenerate]');
                                session('organ_login',true);
                                session('organ_id',$res['uid']);
                                session('is_admin', 0);

                                $this->success('登录成功！',U('Reporter/index'));
                            }


                        }elseif($res && $res['password']!=$data['pass']){
                            $this->error('密码错误！');
                        }else{
                            $this->error('手机号未注册！');
                        }
                    }
                }else{
                    $this->error('参数错误！22');
                }

            }
        }
    }*/

    public function login() {
        C('TOKEN_ON',false);
        if(IS_POST) {
            // 管理员登陆
            $data['email'] = I("post.account");
            $_POST['pass'] = md5(htmlspecialchars_decode(trim(I('post.password'))));

            if ($data['email'] && I("post.password")) {
                $AdminModel = D('Admin');

                $res = $AdminModel->where(array('email' => $data['email']))->find();
                if ($res && $res['password'] == $_POST['pass']) {
                    if ($res['state'] == 0) {
                        session('orgReg_sendEmail', true);
                        session('orgReg_email', $data['email']);
                        $this->success('登录成功！', U('Org/regAction'));
                    } elseif ($res['state'] == 1 && !$res['organ']) {
                        session('organ_id', $res['id']);
                        session('is_admin', 1);
                        $this->success('登录成功！', U('Org/setOrganInfo'));
                        exit;
                    } else {
                        if (I('post.rememberPass') == 1) {
                            session(array('expire' => 3600 * 24 * 90));
                        }
                        session('[regenerate]');
                        session('organ_login', true);
                        session('organ_id', $res['id']);
                        session('is_admin', 1);
                        //$this->success('登录成功！',U('Department/index'));
                        $this->success('登录成功！', U('Reporter/index'));
                        exit;
                    }
                } elseif ($res && $res['password'] != $_POST['pass']) {
                    $this->error('密码错误！'.$res['password'].$_POST['pass']);
                } else {

                    // 记者登陆
                    $account = I("post.account");
                    $pass = I("post.password");
                    if($account && $pass) {
                        $pass = md5(htmlspecialchars_decode(C('PWD_SALT') . trim(I('post.password'))));
                        $map['mobile'] = $account;
                        $map['realname'] = $account;
                        $map['_logic'] = 'OR';

                        /*$frontUserModel = D('FrontUser');
                        $frontUserInfo = $frontUserModel->where($map)->find();
                        if($frontUserInfo && $frontUserInfo['password'] == $pass) {
                            if($frontUserInfo['reporter_id'] > 0) {
                                $power = M('UserPower')->where(array('user_id' => $frontUserInfo['reporter_id']))->select();
                                if(empty($power)) {
                                    $this->error('您无权限登陆！',U('Index/login'));
                                    exit;
                                } else {
                                    if(I('post.rememberPass')==1){
                                        session(array('expire'=>3600*24*90));
                                    }
                                    session('[regenerate]');
                                    session('organ_login',true);
                                    session('organ_id',$frontUserInfo['front_user_id']);
                                    session('is_admin', 0);
                                    session('is_reporter', $frontUserInfo['reporter_id']);

                                    $this->success('登录成功！',U('Reporter/index'));
                                    exit;
                                }
                            } else {

                                if(I('post.rememberPass')==1){
                                    session(array('expire'=>3600*24*90));
                                }
                                session('[regenerate]');
                                session('organ_login',true);
                                session('organ_id',$frontUserInfo['front_user_id']);
                                session('is_admin', 0);
                                session('is_reporter', 0);
                                $this->success('登录成功！',U('Reporter/index'));
                                exit;
                            }


                        } elseif($res && $res['password'] != $pass){
                            $this->error('密码错误！');
                        } else{
                            $this->error('账号未注册！');
                        }*/


                        $UserInfoModel=D('UserInfo');
                        $res=$UserInfoModel->alias('ui')->join('__USER__ u ON ui.uid = u.uid')->where($map)->find();

                        if($res && $res['password']==$pass){

                            $power = M('UserPower')->where(array('user_id' => $res['uid']))->select();
                            if(empty($power)) {
                                if(I('post.rememberPass')==1){
                                    session(array('expire'=>3600*24*90));
                                }
                                session('[regenerate]');
                                session('organ_login',true);
                                session('organ_id',$res['uid']);
                                session('is_type', 0);

                                $this->success('登录成功！',U('Article/index'));
                                exit;

//                                 $this->error('您无权限登陆！',U('Index/login'));
//                                 exit;
                            } else {
                                if(I('post.rememberPass')==1){
                                    session(array('expire'=>3600*24*90));
                                }
                                session('[regenerate]');
                                session('organ_login',true);
                                session('organ_id',$res['uid']);
                                session('is_type', 1);

                                $this->success('登录成功！',U('Reporter/index'));
                                exit;
                            }


                        }elseif($res && $res['password']!=$pass){
                            $this->error('密码错误！');
                        }else{
                            $this->error('账号未注册！');
                        }

                    } else {
                        $this->error('账号不能为空');
                    }
                }

            } else {
                $this->error('参数错误！');
            }
        }
    }


    public function logout(){
        // session('organ_login',null);
        // session('organ_id',null);
        session(null);
        header("Location:".U('Index/index'));
    }


    public function checkMobile(){
        $phone=I('get.phone');
        $info=M('Org')->where(array('operator_tel'=>$phone))->find();
        if(!$info){
            $mess['status']='y';
            $mess['info']='此手机号可以使用！';
        }else{
            $mess['status']='n';
            $mess['info']='此手机号已经使用！';
        }
        $this->ajaxReturn($mess);
    }

    /**
     * 机构信息录入
     * @param int $flag （0：政府 1：媒体 2：企业）
     */
    public function setOrganInfo($flag=0){
        $flag=I('get.flag',0);
        $organ_id=session('organ_id');
        //$organ_id=41;
        $info="";

        if(!in_array($flag,array(0,1,2)) || !$organ_id){
            header("Location:".U('index'));
        }
        if(IS_POST){
            $organ=D('Org');
            if(!$organ->create()){
                $info=$organ->getError();
            }else{
                $data['name']=I('post.name');
                $data['operator_name']=I('post.operator_name');
                $data['operator_id']=I('post.operator_id');
                $data['operator_tel']=I('post.operator_tel');
                $data['admin_id']=session('organ_id');
                $data['operator_tel']=I('post.operator_tel');
                $data['business_license']=I('post.business_license');
                $data['create_time']=$data['update_time']=time();
                $data['type']=$flag;


                $where=array(
                    'operator_id'=>  $data['operator_id'],
                    'operator_tel'=> $data['operator_tel'],
                    'admin_id'=>$data['admin_id'],
                    '_logic'=>'OR'
                );
                $res=$organ->where($where)->find();
                if($res){
                    $this->error("运营者身份证或运营者电话已经使用、此机构已存在");
                }else{
                    $res1=$organ->add($data);
                    $res2=M('Admin')->save(array('organ'=>$res1,'id'=>$data['admin_id']));

                    if($res1 && $res2){
                        $this->success("机构信息录入成功",U('Reporter/index'));
                    }else{
                        $this->error("服务器错误");
                    }
                }
            }
        }else{
            $this->assign('info',$info);
            $this->assign('flag',$flag);
            $this->display();
        }
    }

    public function sendMobileCode(){
        if(session('orgReg_mobileCode_time') && time()-session('orgReg_mobileCode_time')<=60){
            $mess['status']='n';
            $mess['info']='请稍等'.abs(60-time()+session('orgReg_mobileCode_time')).'秒后，重新获取验证码！';
        }else{
            $phone=I('get.phone');
            $reg="/^13[0-9]{9}$|14[0-9]{9}|15[0-9]{9}$|18[0-9]{9}|17[0-9]{9}$/";
            if($phone && preg_match($reg,$phone)){
                $api='http://ucenter.dev.appwuhan.net/openapi/User/sendMobileCode';
                $code="";
                for($i=0;$i<6;$i++){
                    $code.=rand(0,9);
                }
                $post=array(
                    'mobile'=>$phone,
                    'code'=>$code
                );

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $api);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
                $output = curl_exec($ch);
                curl_close($ch);
                $output=json_decode($output,true);
                if($output['resultCode']===0){
                    session('orgReg_mobileCode',$code);
                    session('orgReg_mobileCode_tel',$phone);
                    session('orgReg_mobileCode_time',time());
                    $mess['status']='y';
                    $mess['info']='发送成功！';
                }else{
                    $mess['status']='n';
                    $mess['info']='发送失败，请重试！';
                }
            }else{
                $mess['status']='n';
                $mess['info']='手机格式错误！';
            }
        }
        $this->ajaxReturn($mess);
    }

    public function checkValidCode(){
        $mobileCode=I('get.code');
        $mobileCode_tel=I('get.phone');
        if($mobileCode){
            if(!session('orgReg_mobileCode_tel') || session('orgReg_mobileCode_tel')==$mobileCode_tel || !$mobileCode_tel){
                if(session('orgReg_mobileCode')==$mobileCode){
                    $mess['status']='y';
                    $mess['info']='验证成功！';
                }else{
                    $mess['status']='n';
                    $mess['info']='验证码错误';
                }
            }else{
                $mess['status']='n';
                $mess['info']='请勿修改验证手机号';
            }
        }else{
            $mess['status']='n';
            $mess['info']='参数错误！';
        }
        $this->ajaxReturn($mess);
    }
}
